#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time,tornado,threading,asyncio
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application,  RequestHandler
from tornado import gen
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor

# `pip install futures` for python2

# https://gist.github.com/methane/2185380 参考
 


class MainPage(RequestHandler):
    def get(self):
        self.write(html_content)


MAX_WORKERS = 4
_result = {}


from tornado.concurrent import run_on_executor
class Index(tornado.web.RequestHandler):
 
 
    def get(self):
        name = self.get_argument('name', 'get')
        t = threading.Thread(target=time.sleep, args=(1.5,))
        t.start()
        t.join()
        self.write("hello {}".format(name))

class AddJobHandler(RequestHandler):
    # 必须定义一个executor的属性，然后run_on_executor 注解才管用。
    executor = ThreadPoolExecutor(max_workers=MAX_WORKERS)

    @tornado.gen.coroutine
    def get(self):
        yield tornado.gen.Task(tornado.ioloop.IOLoop.instance().add_timeout, time.time() + 5)
        # yield tornado.gen.sleep(5)
        self.write('sleep for 5s')

    @gen.coroutine
    def get1(self):
        tid = str(int(time.time() * 10000))
        self.background_task(tid)
        self.write(tid)


class JobCheckHandler(RequestHandler):
    def get(self):
        tid = self.get_argument("tid")
        if tid in _result.keys():
            out = _result[tid]  # 结果
            del _result[tid]  # 删除tid的数据。
            self.write(str(out))
        else:
            self.write("")


# main 启动。
 

async def main():
    HTTPServer(Application([
        ("/", Index),
        ("/add_job", AddJobHandler),
        ("/job_check", JobCheckHandler)
    ], debug=True)).listen(9999)
    await asyncio.Event().wait()

if __name__ == "__main__":
    asyncio.run(main())